package dy.com.udp.广播;

import java.io.IOException;
import java.net.*;
import java.util.concurrent.CountDownLatch;

public class Client {
    private static final int PORT = 30000;

    public static void main(String[] args) throws IOException, InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        Listener listener = new Listener(countDownLatch);
        listener.start();
        countDownLatch.await();//等待监听线程开始运行之后再进行广播

        System.out.println("子线程已经countdown，监听线程已经开始");
        broadcast();
        System.in.read();
        listener.exit();
    }

    public static void broadcast() throws IOException {
        System.out.println("客户端开始广播");
        String data = MessageCreator.buildWithPort(PORT);
        DatagramSocket ds = new DatagramSocket();
        byte[] buffer = data.getBytes();
        DatagramPacket dp = new DatagramPacket(buffer, buffer.length,
                InetAddress.getByName("255.255.255.255"), 20000);
        ds.send(dp);
        ds.close();
        System.out.println("客户端完成广播");
    }

    public static class Listener extends Thread {
        boolean flag = true;
        DatagramSocket ds = null;
        CountDownLatch countDownLatch = null;
        byte[] buffer = null;

        Listener(CountDownLatch countDownLatch) {
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            //通知已经启动
            countDownLatch.countDown();
            System.out.println("已经执行countdown，监听线程已经开始");
            try {
                ds = new DatagramSocket(PORT);
                buffer = new byte[512];
                DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
                while (flag) {

                    ds.receive(dp);

                    String ip = dp.getAddress().getHostAddress();
                    int port = dp.getPort();
                    int len = dp.getLength();
                    String data = new String(dp.getData(), 0, len);
                    String sn = MessageCreator.parseSn(data);
                    System.out.println("客户端监听部收到消息，ip：" + ip + ",端口：" + port + ",数据:" + data + ",解析到的sn为：" + sn);


                }

            } catch (Exception e) {

            } finally {
                close();

            }

        }

        public void close() {
            if (ds != null) {
                ds.close();
                ds = null;
            }
        }

        public void exit() {
            flag = false;
            close();
        }
    }
}
